/*
 * @lc app=leetcode.cn id=86 lang=java
 *
 * [86] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if(null == head || null == head.next){
            return head;
        }

        ListNode smallHead = new ListNode();
        ListNode largeHead = new ListNode();
        ListNode smallLast = smallHead;
        ListNode largeLast = largeHead;

        ListNode cur = head;
        ListNode next = head.next;

        while(true){
            if(cur.val < x){
                //if(null == smallHead.next) smallHead.next = cur;
                smallLast.next = cur;
                smallLast = cur;
                smallLast.next = null;
            }else{
                //if(null == largeHead.next) largeHead.next = cur;
                largeLast.next = cur;
                largeLast = cur;
                largeLast.next = null;
            }

            if(null == next) break;
            cur = next;
            next = next.next;
        }
        // printListNode(smallHead);
        // printListNode(largeHead);

        smallLast.next = largeHead.next;

        return smallHead.next;
    }
    public void printListNode(ListNode head){
        while(null!=head){
            System.out.print(head.val);
            head = head.next;
        }
        System.out.println();
    }
}
// @lc code=end

